package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.Book;
import com.bookstore.back.entity.Order;
import com.bookstore.back.entity.OrderItem;
import com.bookstore.back.entity.User;
import com.bookstore.back.mapper.OrderMapper;
import com.bookstore.back.service.BookService;
import com.bookstore.back.service.OrderService;
import com.bookstore.back.service.OrderItemService;
import com.bookstore.back.service.UserService;
import com.bookstore.back.vo.OrderVO;
import com.bookstore.back.vo.OrderItemVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 *
 * @author 程序猿_Ti
 * @since 2025-07-19
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private BookService bookService;

    @Autowired
    private UserService userService;

    @Override
    public IPage<Order> getOrderList(Map<String, Object> params) {
        // 分页参数
        int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
        int size = Integer.parseInt(params.getOrDefault("size", "10").toString());

        // 查询条件
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();

        // 订单号搜索
        String orderNo = (String) params.get("orderNo");
        if (StringUtils.isNotBlank(orderNo)) {
            queryWrapper.like("order_no", orderNo);
        }

        // 状态筛选
        String statusStr = (String) params.get("status");
        if (StringUtils.isNotBlank(statusStr)) {
            Integer status = Integer.parseInt(statusStr);
            queryWrapper.eq("status", status);
        }

        // 用户ID筛选
        String userIdStr = (String) params.get("userId");
        if (StringUtils.isNotBlank(userIdStr)) {
            Integer userId = Integer.parseInt(userIdStr);
            queryWrapper.eq("user_id", userId);
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("created_at");

        // 查询订单列表
        IPage<Order> orderPage = this.page(new Page<>(current, size), queryWrapper);

        // 为每个订单计算商品数量
        List<Order> orders = orderPage.getRecords();
        for (Order order : orders) {
            // 查询该订单的所有订单项
            QueryWrapper<OrderItem> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("order_id", order.getId());
            List<OrderItem> orderItems = orderItemService.list(itemQueryWrapper);

            // 计算商品总数量
            int totalQuantity = orderItems.stream()
                    .mapToInt(OrderItem::getQuantity)
                    .sum();

            // 设置商品数量
            order.setItemCount(totalQuantity);
        }

        return orderPage;
    }

    @Override
    public IPage<OrderVO> getOrderListWithUserInfo(Map<String, Object> params) {
        // 分页参数
        int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
        int size = Integer.parseInt(params.getOrDefault("size", "10").toString());

        // 查询条件
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();

        // 订单号搜索
        String orderNo = (String) params.get("orderNo");
        if (StringUtils.isNotBlank(orderNo)) {
            queryWrapper.like("order_no", orderNo);
        }

        // 状态筛选
        String statusStr = (String) params.get("status");
        if (StringUtils.isNotBlank(statusStr)) {
            Integer status = Integer.parseInt(statusStr);
            queryWrapper.eq("status", status);
        }

        // 用户ID筛选
        String userIdStr = (String) params.get("userId");
        if (StringUtils.isNotBlank(userIdStr)) {
            Integer userId = Integer.parseInt(userIdStr);
            queryWrapper.eq("user_id", userId);
        }

        // 用户名搜索
        String userName = (String) params.get("userName");
        if (StringUtils.isNotBlank(userName)) {
            // 先查询用户ID
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.like("username", userName);
            List<User> users = userService.list(userQueryWrapper);
            if (!users.isEmpty()) {
                List<Integer> userIds = users.stream().map(user -> user.getId().intValue()).collect(Collectors.toList());
                queryWrapper.in("user_id", userIds);
            } else {
                // 如果没有找到用户，返回空结果
                return new Page<>(current, size);
            }
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("created_at");

        // 查询订单
        IPage<Order> orderPage = this.page(new Page<>(current, size), queryWrapper);

        // 转换为OrderVO
        IPage<OrderVO> orderVOPage = new Page<>(current, size, orderPage.getTotal());
        List<OrderVO> orderVOList = orderPage.getRecords().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);

            // 获取用户信息
            User user = userService.getById(order.getUserId().longValue());
            if (user != null) {
                orderVO.setUsername(user.getUsername());

            }

            return orderVO;
        }).collect(Collectors.toList());

        orderVOPage.setRecords(orderVOList);
        return orderVOPage;
    }

    @Override
    public Map<String, Object> getOrderDetail(Integer orderId) {
        Order order = this.getById(orderId);
        if (order == null) {
            return null;
        }

        // 获取订单项
        QueryWrapper<OrderItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("order_id", orderId);
        List<OrderItem> orderItems = orderItemService.list(itemQueryWrapper);

        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("items", orderItems);

        return result;
    }

    @Override
    public Map<String, Object> getOrderDetailWithInfo(Integer orderId) {
        Order order = this.getById(orderId);
        if (order == null) {
            return null;
        }

        // 转换为OrderVO并获取用户信息
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);

        // 获取用户信息
        User user = userService.getById(order.getUserId().longValue());
        if (user != null) {
            orderVO.setUsername(user.getUsername());

        }

        // 获取订单项
        QueryWrapper<OrderItem> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("order_id", orderId);
        List<OrderItem> orderItems = orderItemService.list(itemQueryWrapper);

        // 转换为OrderItemVO列表
        List<OrderItemVO> orderItemVOList = orderItems.stream().map(item -> {
            OrderItemVO itemVO = new OrderItemVO();
            BeanUtils.copyProperties(item, itemVO);

            // 通过图书ID获取作者信息
            if (item.getBookId() != null) {
                Book book = bookService.getById(item.getBookId());
                if (book != null) {
                    itemVO.setBookAuthor(book.getAuthor());
                }
            }

            return itemVO;
        }).collect(Collectors.toList());

        orderVO.setItems(orderItemVOList);

        Map<String, Object> result = new HashMap<>();
        result.put("order", orderVO);
        result.put("items", orderItemVOList);

        return result;
    }

    @Override
    @Transactional
    public boolean updateOrderStatus(Integer orderId, Integer status) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(status);

        // 根据状态设置相应的时间
        LocalDateTime now = LocalDateTime.now();
        switch (status) {
            case 1: // 已支付
                order.setPaymentTime(now);
                break;
            case 2: // 已发货
                order.setShippingTime(now);
                break;
            case 3: // 已完成
                order.setCompletionTime(now);
                // 订单完成时，更新相关图书的销量
                updateBookSalesOnOrderCompletion(orderId);
                break;
            case 4: // 已取消
                order.setCancelTime(now);
                break;
        }

        return this.updateById(order);
    }

    @Override
    public boolean shipOrder(Integer orderId) {
        return updateOrderStatus(orderId, 2); // 设置为已发货状态
    }

    @Override
    public boolean cancelOrder(Integer orderId, String reason) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(4); // 已取消
        order.setCancelTime(LocalDateTime.now());
        order.setCancelReason(reason);

        return this.updateById(order);
    }

    @Override
    public List<Order> getRecentOrders(Integer limit) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at")
                   .last("LIMIT " + (limit != null ? limit : 10));

        return this.list(queryWrapper);
    }

    @Override
    public Map<String, Object> getOrderStats() {
        Map<String, Object> stats = new HashMap<>();

        // 总订单数
        long totalOrders = this.count();
        stats.put("totalOrders", totalOrders);

        // 待支付订单数
        QueryWrapper<Order> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.eq("status", 0);
        long pendingOrders = this.count(pendingWrapper);
        stats.put("pendingOrders", pendingOrders);

        // 已完成订单数
        QueryWrapper<Order> completedWrapper = new QueryWrapper<>();
        completedWrapper.eq("status", 3);
        long completedOrders = this.count(completedWrapper);
        stats.put("completedOrders", completedOrders);

        // 总销售额（已完成订单）
        List<Order> completedOrderList = this.list(completedWrapper);
        BigDecimal totalSales = completedOrderList.stream()
                .map(Order::getActualAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        stats.put("totalSales", totalSales);

        return stats;
    }

    /**
     * 订单完成时更新相关图书的销量
     *
     * @param orderId 订单ID
     */
    private void updateBookSalesOnOrderCompletion(Integer orderId) {
        try {
            // 获取订单项列表
            QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderId);
            List<OrderItem> orderItems = orderItemService.list(queryWrapper);

            // 更新每本书的销量
            for (OrderItem item : orderItems) {
                Book book = bookService.getById(item.getBookId());
                if (book != null) {
                    // 累加销量
                    int newSales = (book.getSales() != null ? book.getSales() : 0) + item.getQuantity();
                    book.setSales(newSales);
                    bookService.updateById(book);
                }
            }
        } catch (Exception e) {
            // 记录日志但不影响主流程
            System.err.println("更新图书销量失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

}
